package com.sample.springbatch.job.sample.reader;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.database.JpaPagingItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * Jpa 分页读取数据库
 * Created by zwg on 2017/8/8.
 */
@Component
public class UserJpaPagingItemReader<User> extends JpaPagingItemReader {

    private Logger logger1 = LoggerFactory.getLogger(UserJpaPagingItemReader.class);

    @Autowired
    EntityManagerFactory entityManagerFactory;

    public UserJpaPagingItemReader() {
        setPageSize(5);
        setQueryString("select u from User u where age = :age");
        Map<String, Object> params = new HashMap<>();
        try{
            params.put("age", 10);
        }catch (Exception e){

        }

        setTransacted(false);

        setParameterValues(params);
        setSaveState(false);
    }


    @PostConstruct
    public void init(){
        setEntityManagerFactory(entityManagerFactory);
    }



    @Override
    @SuppressWarnings("unchecked")
    protected void doReadPage() {
        Long start = System.currentTimeMillis();
        super.doReadPage();
        logger1.info("doReadPage time:{}",(System.currentTimeMillis()-start));
    }

}
